define(['jquery', 'bootstrap', 'backend', 'form', 'table'], function ($, undefined, Backend, Form, Table) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'qingdongwms/event/event/index',
                    add_url: 'qingdongwms/event/event/add',
                    detail_url : 'qingdongwms/event/event/detail',
                    table: 'approval'
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url+'?createtime='+Fast.api.query("createtime"),
                sortName: 'id',
                columns: [
                    [
                        {field: 'state', checkbox: true},
                        {field: 'title', title: __('标题'), operate:"like", formatter: function (value, row) {
                            console.log(row.relation_type)
                            if(row.relation_type == 'event'){
                                return "<a href='javascript:void(0);' data-id='" + row.id + "' class='show-event-detail'>" + value + "</a>";
                            }else{
                                return '';
                            }

                        }},
                        // {field: 'event_type', title: __('类型'), operate:"like"},
                        {field: 'start_time', title: __('开始时间'), operate:false},
                        {field: 'end_time', title: __('结束时间'), operate:false},
                        {field: 'create_staff.name', title: __('创建人'), operate:false},
                        {field: 'staff.name', title: __('负责人'), operate:false},
                        {field: 'owner_staff.name', title: __('执行人'), operate:false},
                        {field: 'reminds_staff.name', title: __('抄送人'), operate:false},
                        {field: 'status', title: __('状态'),formatter:Table.api.formatter.status,
                            searchList: {'0':'未开始', 1:'执行中',2:'已结束',3:'已取消',}},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},

                    ]
                ],
                //启用普通表单搜索
                commonSearch: true,
                searchFormVisible: true,
                onLoadSuccess:function(){
                    // 这里就是数据渲染结束后的回调函数
                    $(".btn-add").data("area",["80%","80%"]);
                    $(".btn-edit").data("area",["80%","80%"]);
                }
            });
            $(document).on('click', '.show-event-detail', function () {
                var id = $(this).data('id');
                var area = [$(window).width() > 1200 ? '1200px' : '95%', $(window).height() > 800 ? '800px' : '95%'];
                var options = {
                    shadeClose: false,
                    shade: [0.3, '#393D49'],
                    area: area,
                };
                Fast.api.open("qingdongwms/event/event/detail?ids=" + id, '任务详情', options);
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
            $('.search').hide();
            $('.btn-import').hide();

        },
        add: function () {
            Controller.api.bindevent();
        },

        add_needs: function () {
            Controller.api.bindevent();
        },

        revoke: function () {
            Form.api.bindevent($("form[role=form]"), function(data, ret){
                //这里是表单提交处理成功后的回调函数，接收来自php的返回数据
                Fast.api.close(data);//这里是重点
                parent.location.reload();
            });
        },

        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            // 初始化表格参数配置
            Table.api.init({});
            var ids=$('#ids').val();
            //费用
            var table5 = $("#consume");
            // 初始化表格
            table5.bootstrapTable({
                url          : 'qingdongwms/event/event/get_consume?ids=' + ids,
                pk           : 'id',
                sortName     : 'id',
                toolbar:'#toolbar_consume',
                operate      : false,
                commonSearch : false,
                search       : false,
                visible      : false,
                showColumns  : false,
                showExport   : false,
                showToggle   : false,
                columns      : [
                    [
                        {field : 'submit_date', title : '申请日期'},
                        {
                            field: 'number',
                            title: '费用编号',
                            fixedColumns: true,
                            formatter: function (value, row, index) {
                                if (row.number == null) {
                                    return "<a href='javascript:void(0);' data-id='" + row.id + "' class='show-consume-detail'>无</a>";
                                } else {
                                    return "<a href='javascript:void(0);' data-id='" + row.id + "' class='show-consume-detail'>" + row.number + "</a>";
                                }

                            },
                            operate: 'like'
                        },
                        {field : 'title', title : '费用标题'},
                        {field : 'money', title : '报销总金额'},
                        {field : 'staff.name', title : '创建人'},
                        {field : 'createtime', title : '创建时间'},
                        {field : 'check_status', title : '状态', formatter : Table.api.formatter.status,
                            searchList : {0 : '待审核', 1 : '审核中', 2 : '审核通过', 3 : '审核未通过', 4 : '撤销', 5 : '草稿(未提交)'},operate:false},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table5);

            $(document).on('click', '.show-consume-detail', function (data) {
                var area = [$(window).width() > 1200 ? '1200px' : '95%', $(window).height() > 800 ? '800px' : '95%'];
                var options = {
                    shadeClose: false,
                    shade: [0.3, '#393D49'],
                    area: area,
                    callback: function (value) {
                        //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                        console.log(value);
                    }
                };
                Fast.api.open("qingdongwms/finance/consume/detail" + "?ids=" + $(this).data('id'), '费用详情页', options);
            }).on('click','.btn-set_team',function () {
                var id=$('#ids').val();
                Fast.api.open("qingdongwms/event/event/set_team?ids="+id, "团队修改",{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    area:["90%","90%"],
                    callback:function () {
                        location.reload()
                    }
                });
            }).on('click', '.btn-edit', function (data) {
                var area = [$(window).width() > 1200 ? '1200px' : '95%', $(window).height() > 800 ? '800px' : '95%'];
                var options = {
                    shadeClose: false,
                    shade: [0.3, '#393D49'],
                    area: area,
                    callback: function (value) {
                        //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                        console.log(value);
                    }
                };
                Fast.api.open("qingdongwms/event/event/edit" + "?ids=" + ids, '编辑费用', options);
            });

            //客户需求
            var table6 = $("#needs_table");
            // 初始化表格
            table6.bootstrapTable({
                url          : 'qingdongwms/event/event/get_needs_list?event_id=' + ids,
                pk           : 'id',
                sortName     : 'id',
                toolbar      : '#needs_customer',
                operate      : false,
                commonSearch : false,
                search       : false,
                visible      : false,
                showColumns  : false,
                showExport   : false,
                showToggle   : false,
                columns      : [
                    [
                        {field : 'createtime', title : '提交日期',width:200},
                        {field : 'needs', title : '客户需求'},
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table6);
            Controller.api.bindevent();
        },
        set_team    : function () {
            $(document).on('click','.btn-zhidu',function () {
                $(this).parent().parent().find('.is_edit').html('只读')
                $(this).parent().parent().find('.staff_is_edit').val(0)
                $(this).parent().find('.btn-duxie').show()
                $(this).hide()
                layer.msg('权限更改为只读')
            })
            $(document).on('click','.btn-duxie',function () {
                $(this).parent().parent().find('.is_edit').html('读写')
                $(this).parent().parent().find('.staff_is_edit').val(1)
                $(this).parent().find('.btn-zhidu').show()
                $(this).hide()
                layer.msg('权限更改为读写')
            })
            $(document).on('click','.btn-delone',function () {
                $(this).parent().parent().remove()
            }).on('click','.btn-add_team',function () {
                var ids=$('#id').val();
                Fast.api.open("qingdongwms/event/event/add_team?ids="+ids, '添加团队成员',{
                    shadeClose: false,
                    shade: false,
                    maxmin: false,
                    moveOut: false,
                    scrollbars:false,
                    'area':[
                        $(window).width() > 800 ? '80%' : '80%',
                        $(window).height() > 600 ? '80%' : '80%'
                    ],
                    callback:function(value){
                        if (value.is_edit == 1){
                            var edit_html = '读写';
                        }else{
                            var edit_html = '只读';
                        }

                        var html = '<tr>\n' +
                            '           <input type="hidden" name="row[staff][{$key+1}][id]" value="'+value.id+'"/>\n' +
                            '           <input type="hidden" name="row[staff][{$key+1}][is_edit]" class="staff_is_edit" value="'+value.is_edit+'"/>\n' +
                            '           <input type="hidden" name="row[staff][{$key+1}][roles]" value="2"/>\n' +
                            '           <td class="text-center">'+value.name+'</td>\n' +
                            '           <td class="text-center">'+value.post+'</td>\n' +
                            '           <td class="text-center is_edit">'+edit_html+'</td>\n' +
                            '           <td class="text-center">\n';
                        if (value.is_edit == 1){
                            html += '              <a class="btn btn-xs btn-info btn-zhidu">只读</a>\n' +
                                '              <a class="btn btn-xs btn-info btn-duxie" style="display: none">读写</a>\n';
                        }else{
                            html += '              <a class="btn btn-xs btn-info btn-zhidu" style="display: none">只读</a>\n' +
                                '              <a class="btn btn-xs btn-info btn-duxie">读写</a>\n';
                        }

                        html += '              <a href="javascript:;" class="btn btn-xs btn-danger btn-delone"   data-original-title="删除"><i class="fa fa-trash"></i></a>\n' +
                            '           </td>\n' +
                            '        </tr>';
                        $('#table-team').append(html)
                        Form.events.plupload("#plupload-local");
                        //   在这里可以接收弹出层中使用`Fast.api.close(data)`进行回传数据
                    },
                });
            })

            Controller.api.bindevent();
        },

        add_team    : function () {
            Form.api.bindevent($("form[role=form]"), function(data, ret){
                //这里是表单提交处理成功后的回调函数，接收来自php的返回数据
                Fast.api.close(data);//这里是重点
            });
        },
        api: {
            bindevent: function () {
                // 服务方式
                $('#c-event_type_1').on('change',function (){
                    var event_type_1=$('#c-event_type_1').val();
                    var type2=$('#c-event_type_2').data('value');
                    var type3=$('#c-event_type_3').data('value');

                    var event_type_2_html='';
                    var event_type_3_html='';
                    var type2_list=[];
                    var type3_list=[];
                    if(event_type_1 == '客户服务'){
                         type2_list=['上门'];
                        event_type_2_html="<option value=\"\">请选择服务方式</option>";
                        $.each(type2_list,function (index,value){
                            if(type2 == value){
                                event_type_2_html+="<option selected='selected' value=\""+value+"\">"+value+"</option>";
                            }else{
                                event_type_2_html+="<option value=\""+value+"\">"+value+"</option>";
                            }

                        })
                         type3_list=['认识','报价','签合同','收款'];
                        event_type_3_html="<option value=\"\">请选择服务目的</option>";
                        $.each(type3_list,function (index,value){
                            if(type3 == value){
                                event_type_3_html+="<option selected='selected' value=\""+value+"\">"+value+"</option>";
                            }else{
                                event_type_3_html+="<option value=\""+value+"\">"+value+"</option>";
                            }
                        })
                    }else{
                         type2_list=['上门','电话','返厂维修'];
                        event_type_2_html="<option value=\"\">请选择计划类型</option>";
                        $.each(type2_list,function (index,value){
                            if(type2 == value) {
                                event_type_2_html += "<option selected='selected' value=\"" + value + "\">" + value + "</option>";
                            }else{
                                event_type_2_html += "<option value=\"" + value + "\">" + value + "</option>";
                            }
                        });
                        type3_list=['上门安装','上门维修'];
                        event_type_3_html="<option value=\"\">请选择服务目的</option>";
                        $.each(type3_list,function (index,value){
                            if(type3 == value) {
                                event_type_3_html += "<option selected='selected' value=\"" + value + "\">" + value + "</option>";
                            }else{
                                event_type_3_html += "<option value=\"" + value + "\">" + value + "</option>";
                            }
                        });
                    }
                    $('#c-event_type_2').html(event_type_2_html);
                    $('#c-event_type_3').html(event_type_3_html);
                }).trigger('change');

                //服务目的
                $('#c-event_type_2').on('change',function (){
                    var event_type_2=$('#c-event_type_2').val();
                    if(event_type_2 != '上门'){
                        $('#event_type_3').hide();
                    }else{
                        $('#event_type_3').show();
                    }

                }).trigger('change');
                //服务
                $('#c-event_type_3').on('change',function (){
                    var event_type_3=$('#c-event_type_3').val();
                }).trigger('change');

                $(document).on("fa.event.appendfieldlist", '.fieldlist', function(){
                    //通用的表单组件事件绑定和组件渲染
                    Form.events.selectpage($("form"));
                    Form.events.datetimepicker($("form"));
                    Form.events.plupload($("form"));
                    $(".product").data("params", function (obj) {
                        var customer_id=$('#c-customer_id').val();
                        if(!customer_id){
                            layer.alert('请先选择客户');
                            return false;
                        }
                        return {customer_id: customer_id};
                    });
                    $(".customer_product").data("params", function (obj) {
                        var customer_id=$('#c-customer_id').val();
                        if(!customer_id){
                            layer.alert('请先选择客户');
                            return false;
                        }
                        return {customer_id: customer_id};
                    });
                }).on("click", ".select-customer", function(){
                    var $this=$(this);
                    top.Fast.api.open($(this).data("url") , __('Select'), {callback: function (data) {
                            $this.html(data.name);
                            $('[name="'+$this.data('name')+'"]').val(data.id);
                        },area:["100%", "100%"]});
                }).on("click", ".select-parts", function(){
                    var $this=$(this);
                    top.Fast.api.open($(this).data("url") , __('Select'), {callback: function (data) {
                            $this.html(data.name);
                            $('[name="'+$this.data('name')+'"]').val(data.id);
                        },area:["100%", "100%"]});
                }).on("click", ".select-product", function(){
                    var $this=$(this),customer_id=$('[name="row[relation_id]"]').val();
                    if(!customer_id){
                        Layer.msg('请先选择客户');
                        return false;
                    }
                    top.Fast.api.open($(this).data("url")+"&customer_id="+customer_id, __('Select'), {callback: function (data) {
                            $this.html(data.product.name);
                            $('[name="'+$this.data('name')+'"]').val(data.id);

                            $(".fieldlist input:eq(2)").trigger("change");
                        },area:["100%", "100%"]});
                }).on("click", ".select-contacts", function(){
                    var $this=$(this),customer_id=$('[name="row[relation_id]"]').val();
                    if(!customer_id){
                        Layer.msg('请先选择客户');
                        return false;
                    }
                    top.Fast.api.open($(this).data("url")+"&customer_id="+customer_id, __('Select'), {callback: function (data) {
                            $this.html(data.name);
                            $('[name="'+$this.data('name')+'"]').val(data.id);

                            $(".fieldlist input:eq(2)").trigger("change");
                        },area:["100%", "100%"]});
                });
                Form.api.bindevent($("form[role=form]"), function(data, ret){
                    //这里是表单提交处理成功后的回调函数，接收来自php的返回数据
                    Fast.api.close(data);//这里是重点
                });
            },
            formatter: {
                thumb: function (value, row, index) {
                    var style = row.storage == 'upyun' ? '!/fwfh/120x90' : '';
                    return '<img src="' + row.image + '" data-tips-image alt="" title="封面图" style="max-height:90px;max-width:120px">';

                },

            }
        }

    };
    return Controller;
});